package cn.zcscloud.controller;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/file")
public class FileController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        switch (action){
            case "downLoad":
                this.downLoad(req,resp);
        }
    }



    private void downLoad(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取文件名
        String filename = req.getParameter("filename");
        //获取输入流对象
        FileInputStream fis = new FileInputStream("E:\\file\\" + filename);
        //获取输出流对象
        ServletOutputStream os = resp.getOutputStream();
        //设置浏览器解析方式
        resp.setHeader("content-Disposition","attachment;filename="+filename);
        //io对拷
        IOUtils.copy(fis,os);
        //关流释放资源
        fis.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
